package com.nineclock.message.service.impl;

import com.nineclock.message.config.JPushManager;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JPushManager jPushManager;

    /**
     * 1. 存储消息到 mongo
     * 2. 推送消息给管理员
     * @param message
     */
    @Override
    public void pushSingleMessage(NcMessage message) throws Exception {
        //1. 存储消息到 mongo
        mongoTemplate.save(message);
        //2. 推送消息给管理员(申请人)
        jPushManager.sendNotificationByAlias
                (message.getTitle(), message.getContent(), message.getTargets(), null);
    }

    /**
     * 从 mongo查询数据
     * @param messageDTO
     * @return
     */
    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {

        Query query = new Query();
        //where 列 is ：具体的值
        // column = 1
        if(messageDTO.getId() != null){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if(messageDTO.getType() != null){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if(messageDTO.getUserId() != null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }

        if(messageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);

        return messageList;
    }

    @Override
    public void updateMessageWithApproved(String messageId) {
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));

        //要更新的信息
        Update update = new Update();
        update.set("useStatus", 1);
        update.set("approveStatue", 1);
        update.set("title", "团队申请通过");


        mongoTemplate.updateFirst(query, update , NcMessage.class);
    }
}
